package com.storydo.file.share.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.storydo.file.share.exception.BaseException;

import lombok.extern.slf4j.Slf4j;

/**   
* @Title: ZipUtil.java 
* @Description: TODO
* @author : Storydo
* @date: 2021年4月26日 下午3:33:24 
* @version:V1.0 
* Copyright 悦享互联 2016 All right reserved.
* Modification  History:
* Version       Date          Author          Description
* ----------------------------------------------------------------------------
*  1.0         2021年4月26日        Storydo              TODO
*/
@Slf4j
public class FileUtil {

	public static void zip(ZipOutputStream out, File f) throws Exception {
		zip(out, f, "");
	}
	
	
	private static void zip(ZipOutputStream out, File f, String base) throws Exception {	
		if (f.isDirectory()) { // 测试此抽象路径名表示的文件是否是一个目录
			File[] fl = f.listFiles(); // 获取路径数组
			out.putNextEntry(new ZipEntry(base + "/")); 
			base = base.length() == 0 ? "" : base + "/";
			for (File file : fl) {
				zip(out, file, base + file.getName());
			}
		} else {
			out.putNextEntry(new ZipEntry(base)); 
			try(BufferedInputStream bis =  new BufferedInputStream(new FileInputStream(f))) {
				byte[] ba = new byte[2048]; int len = -1;
				while ((len = bis.read(ba)) != -1) {
					out.write(ba, 0, len);
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
	}
	
	/**
	 * 
	* @Description: 删除文件夹、、、
	* @param path
	* @author: Storydo
	* @date: 2021年4月27日 下午3:02:23
	 */
	public static void deleteDir(File path) {
		if (path == null || path.getAbsolutePath().length() < 5) {
			throw new BaseException("路径错误");
		}
		if (path.isDirectory()) {
			for (File element : path.listFiles()) {
				deleteDir(element);
			}
		} 
		path.delete();
	
	}
}
